開始前一樣可以先讀這篇卡斯伯的大補帖
https://wcc723.github.io/javascript/2017/06/29/es6-native-array/
還有這篇關於Splice、Slice、Split的區別
https://github.com/sawyerbutton/Difference-between-Splice-Slice-Split
練習目標 :
some()
every()
find()
findIndex()
splice()
slice()
資料結構:
const people = [
{ name: "Wes", year: 1988 },
{ name: "Kait", year: 1986 },
{ name: "Irv", year: 1970 },
{ name: "Lux", year: 2015 },
];
const comments = [
{ text: "Love this!", id: 523423 },
{ text: "Super good", id: 823423 },
{ text: "You are the best", id: 2039842 },
{ text: "Ramen is my fav food ever", id: 123523 },
{ text: "Nice Nice Nice!", id: 542328 },
];
今天的操作很簡單,所以就也一起帶入ES6的寫法做比較。
1.some() : 只要陣列中有其中一項符合條件就return true
is at least one person 19 or older?
陣列中是否至少有一個19歲或以上的人
const isAdult = people.some(function (person) {
const currentYear = new Date().getFullYear();
return currentYear - person.year >= 19;
});
ES6寫法:
const isAdult = people.some (
person => ((new Date()).getFullYear()) - person.year >= 19);
2.every() : 陣列中全部都符合條件才return true
is everyone 19 or older?
陣列中是否全部的人都是19歲或以上的人
const allAdults = people.every(function (person) {
const currentYear = new Date().getFullYear();
return currentYear - person.year >= 19;
});
ES6寫法:
const allAdults = people.every (
person => ((new Date()).getFullYear()) - person.year >= 19);
3.find()
find the comment with the ID of 823423
找到陣列中ID為823423的評論
const comment = comments.find(function (comment) {
return comment.id === 823423;
});
ES6寫法:
const comment = comments.find((comment) => comment.id === 823423);
4.findIndex()
delete the comment with the ID of 823423
刪除陣列中ID為823423的評論
先利用findIndex()找出評論在陣列的哪一個位置
const index = comments.findIndex(function (comment) {
return comment.id === 823423;
});
ES6寫法:
const index = comments.findIndex((comment) => comment.id === 823423);
找出位置後,使用splice()或slice()的方法刪除
splice() : 會影響原始的陣列,不需要再重新命名
comments.splice(index, 1)
slice() : 不會修改原本的陣列,而是回傳由原本的陣列淺層複製的元素。
const newComments = [
...comments.slice(0, index),
...comments.slice(index + 1),
];
今天的練習完成囉,完整的程式碼請直接點擊下方codePen連結
codePen
或者也可以直接到WES BOS的網站下載打包好的檔案
javascript30